from flask import Flask, request, jsonify
import os
import subprocess
import uuid
import base64
import json  # 确保导入了 json 模块
import traceback  # 用于获取完整的错误堆栈信息
import datetime  # 用于生成日志时间戳

app = Flask(__name__)
UPLOAD_FOLDER = '/tmp/uploads'
OUTPUT_FOLDER = '/tmp/output'
LOG_FOLDER = '/tmp/logs'  # 日志文件夹
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
os.makedirs(LOG_FOLDER, exist_ok=True)  # 创建日志文件夹

def log_error(message):
    """
    将错误信息写入日志文件
    """
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_filename = os.path.join(LOG_FOLDER, "error_log.txt")
    
    with open(log_filename, "a") as log_file:
        log_file.write(f"[{timestamp}] ERROR: {message}\n")

@app.route('/process', methods=['POST'])
def handle_base64_image():
    # 解析请求数据
    data = request.get_json()
    if not data or 'image_base64' not in data:
        error_message = "Missing image_base64 field"
        log_error(error_message)  # 记录错误日志
        return jsonify({"error": error_message}), 400
    
    base64_str = data['image_base64']
    
    try:
        # 生成唯一文件名
        file_id = str(uuid.uuid4())
        input_path = os.path.join(UPLOAD_FOLDER, f"{file_id}.png")

        # 清理Base64前缀
        if 'base64,' in base64_str:
            base64_str = base64_str.split('base64,')[-1]

        # 解码并保存文件
        image_data = base64.b64decode(base64_str)
        with open(input_path, 'wb') as f:
            f.write(image_data)

        # 运行处理流程
        subprocess.run([
            "python3", "run_pipeline.py",
            input_path, file_id
        ], check=True, capture_output=True)

        # 读取生成的JSON
        with open(f"{file_id}_response.json") as f:
            result = json.load(f)

        return jsonify(result)

    except subprocess.CalledProcessError as e:
        error_message = f"Processing failed: {e.stderr.decode()}"
        log_error(error_message)  # 记录错误日志
        return jsonify({
            "error": "Processing failed",
            "details": e.stderr.decode()
        }), 500
    except Exception as e:
        error_message = f"Base64 decoding failed: {str(e)}"
        log_error(error_message)  # 记录错误日志
        return jsonify({
            "error": "Base64 decoding failed",
            "details": str(e)
        }), 400
    finally:
        # 清理临时文件
        temp_files = [
            input_path,
            f"{file_id}_cut.json",
            f"{file_id}_fixed_tmp.json",
            f"{file_id}_normalize_json.json",
            f"{file_id}_response.json"
        ]
        for f in temp_files:
            try:
                if f and os.path.exists(f):
                    os.remove(f)
            except Exception as e:
                error_message = f"Error deleting {f}: {str(e)}"
                log_error(error_message)  # 记录错误日志
                print(error_message)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=86)
